package cm.example.shoppingplatformspringboot.mapper;

import cm.example.shoppingplatformspringboot.entity.ShopCarDTO;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface CartMapper {
    // 根据用户id查看购物车
    @Select("SELECT s.*, c.goodid, c.num, g.name, g.image, g.sale_price FROM wn_shopcar s " +
            "LEFT JOIN wn_caritem c ON s.gooditemid = c.id " +
            "LEFT JOIN  wn_goods g ON c.goodid = g.id " +
            "WHERE s.userid = #{userId} " +
            "ORDER BY s.id DESC")
    List<ShopCarDTO> selectCartByUserId(int userId);

    // 插入商品项到 wn_caritem，返回自增ID到 gooditemid
    @Insert("INSERT INTO wn_caritem (userid, goodid, num) VALUES (#{userid}, #{goodid}, #{num})")
    @Options(useGeneratedKeys = true, keyProperty = "gooditemid", keyColumn = "id")
    int insertCartItem(ShopCarDTO shopCarDTO);

    // 插入关联关系到 wn_shopcar
    @Insert("INSERT INTO wn_shopcar (userid, gooditemid) VALUES (#{userid}, #{gooditemid})")
    int insertShopCart(int userid, int gooditemid);

    // 根据 userid 和 goodid 查询商品项
    @Select("SELECT id, userid, goodid, num FROM wn_caritem WHERE userid = #{userid} AND goodid = #{goodid}")
    ShopCarDTO selectByUserIdAndGoodId(@Param("userid") int userid, @Param("goodid") int goodid);

    // 更新商品项数量
    @Update("UPDATE wn_caritem SET num = #{num} WHERE id = #{id}")
    int updateCartItemNum(@Param("id") int id, @Param("num") int num);

    // 查询商品项所属用户ID（用于验证）
    @Select("SELECT userid FROM wn_caritem WHERE id = #{gooditemid}")
    Integer getUserIdByGoodItemId(int gooditemid);

    // 根据用户ID和商品项ID删除购物车关联记录
    @Delete("DELETE FROM wn_shopcar WHERE userid = #{userid} AND gooditemid = #{gooditemid}")
    int deleteShopCart(@Param("userid") int userid, @Param("gooditemid") int gooditemid);

    // 根据商品项ID删除商品项
    @Delete("DELETE FROM wn_caritem WHERE id = #{gooditemid}")
    int deleteCarItem(@Param("gooditemid") int gooditemid);

    // 根据用户ID删除购物车关联记录
    @Delete("DELETE FROM wn_shopcar WHERE userid = #{userid}")
    int deleteAllShopCartByUserId(@Param("userid") int userid);

    // 根据用户ID删除所有商品项
    @Delete("DELETE FROM wn_caritem WHERE userid = #{userid}")
    int deleteAllCarItemsByUserId(@Param("userid") int userid);
}
